package com.wzqj.agent.web.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wzqj.agent.common.ConfigHelper;
import com.wzqj.agent.common.SoaConfig;
import com.wzqj.agent.common.constant.WebConstant;
import com.wzqj.agent.common.exception.BusinessErrorType;
import com.wzqj.agent.common.exception.BusinessException;
import com.wzqj.agent.common.redis.CacheCallback;
import com.wzqj.agent.common.redis.CacheClient;
import com.wzqj.agent.common.redis.CacheKey;
import com.wzqj.agent.web.dao.AgentDao;
import com.wzqj.agent.web.dao.AgentMerchantDao;
import com.wzqj.agent.web.dao.MerchantStoreDao;
import com.wzqj.agent.web.dao.SaleMerchantDao;
import com.wzqj.agent.web.dao.SalesDao;
import com.wzqj.agent.web.dao.UserDao;
import com.wzqj.agent.web.domain.Agent;
import com.wzqj.agent.web.domain.AgentMerchant;
import com.wzqj.agent.web.domain.MerchantStore;
import com.wzqj.agent.web.domain.SaleMerchant;
import com.wzqj.agent.web.domain.Sales;
import com.wzqj.agent.web.domain.User;
import com.wzqj.agent.web.service.AgentService;
import com.wzqj.agent.web.service.MerchantService;
import com.wzqj.agent.web.service.SalesService;
import com.wzqj.wsp.encrypt.MD5;
import com.wzqj.wsp.response.ResponseValue;
import com.wzqj.wsp.response.ResultStatus;
import com.wzqj.wsp.soa.SOAUtil;
@Service("merchantService")
public class MerchantServiceImpl implements MerchantService {

	/**
     * 商户平台服务
     */
    private static final String WMP_PROVIDER_APP_CODE = ConfigHelper.getProperty("WMP_PROVIDER_APP_CODE");

    /**
     * 用户店铺列表
     */
    private static final String WMP_USER_STORES_URL = "merchant/getUserMerchantByWhere";
    
    /**
     * 根据mcode获取门店信息列表（备用）
     */
    private static final String WMP_MERCHANT_BY_MCODES_URL = "merchant/listBymcodes";
	/**
     * 根据资质id获取资质信息
     */
    private static final String WMP_QUALIFICATION_SEARCH_URL = "qualification/getQualificationById";
    /**
     * 根据资质id获取商户平台用户信息
     */
    private static final String WMP_USER_BY_QUALIFICATION_URL = "user/getUserByQualificationId";
    /**
     * 根据手机号获取用户信息
     */
    private static final String WMP_MERCHANT_SEARCH_URL = "user/getUserByMobile";
    /**
     * 注册商户用户
     */
    private static final String WMP_MERCHANT_REGISTER_URL = "user/webRegUser";
    
    /**
     * 添加资质认证
     */
    private static final String WMP_QUALIFICATION_ADD_URL = "qualification/addOrUpdateQualification";
	/**
	 * 设置缓存时间(单位：秒)
	 */
    private static final int CACHE_TIME = 60 * 5; 
    /**
     * 开通商户参数：商户类型
     */
    private static final int ISADMIN = 1;//1：小微商户
    /**
     * 开通商户参数：商户账户类型
     */
    private static final int USERTYPE = 2;//2：小微商户
    
    @Autowired
    private UserDao userDao;
	@Autowired
	private  SaleMerchantDao saleMerchantDao;
	@Autowired
	private  SalesService salesService;
	@Autowired
	private  SalesDao salesDao;
	@Autowired
	private  MerchantStoreDao merchantStoreDao;
	@Autowired
	private AgentService agentService;
	@Autowired
	private AgentDao agentDao;
	@Autowired
	private AgentMerchantDao agentMerchantDao;
	@Autowired
	private CacheClient cacheClient;
	/**
	 * 用户绑定的商户
	 * 参数：userId,mcode,phone
	 */
	@Override
	public JSONArray merchantListPage(final Map<String, Object> params) {
		
		Object vaObject = cacheClient.getAndSetNx(CacheKey.商户列表令牌 + params, CACHE_TIME, new CacheCallback() {
			
			@Override
			public Object execute(CacheClient cacheClient) {
				
				JSONArray merchants = new JSONArray();
				Integer userId = (Integer)params.get("userId");
				String phone = (String)params.get("phone");
				String mcode = (String)params.get("mcode");
				System.out.println();
				System.out.println("merchantListPage--params:userId"+userId+"/mcode"+mcode+"/phone"+phone);
				//根据商户平台手机号进行查询商户列表
				if (!StringUtils.isEmpty(phone)) {
					JSONObject merchant = getMerchantByPhone(userId,phone);
					merchants.add(merchant);
					return merchants;
				}
				//--------------------------------
				//根据商户mcode进行查询商户列表
				if (!StringUtils.isEmpty(mcode)) {
					JSONObject merchant = getMerchantByMcode(userId,mcode);
					merchants.add(merchant);
					return merchants;
				}
				//--------------------------------
				//无条件查询商户列表
				
				 merchants = getMerchants(userId);
				
				//--------------------------------
				if (merchants!=null) {
					//System.out.println("merchants:"+merchants.toString());
					return merchants;
				}
				return null;
			}
		});
		return (JSONArray)vaObject;
	}

	public JSONArray getMerchants(Integer userId){
		JSONArray merchants = new JSONArray();
		JSONObject soaParam = SoaConfig.getSoaParam();
		
		//根据用户查询代理商
		List<Agent> agents = agentService.getByUser(userId);
		User user1 = userDao.getById(userId);
		if (user1.getType()==WebConstant.user_type_agent) {
			Agent agent = agentDao.getById(user1.getTypeId());
			agents.add(agent);
		}
		
		//根据代理商循环查询商户
		for (Agent agent : agents) {
			List<AgentMerchant> agentMerchants = agentMerchantDao.getByAgent(agent.getId().longValue());
			if (agentMerchants!=null&&agentMerchants.size()>0) {
				//循环获取商户id
				for (AgentMerchant agentMerchant : agentMerchants) {
					JSONObject merchant = new JSONObject();
					String merId = agentMerchant.getMerId();
					merchant.put("qualificationId", merId);
					if (!StringUtils.isEmpty(merId)) {
						//调取商户平台接口，获取商户平台用户信息
						JSONObject param1 = new JSONObject();
						param1.put("qualificationId", merId);
						ResponseValue userRv = SOAUtil.getResValFromSOA(WMP_PROVIDER_APP_CODE, WMP_USER_BY_QUALIFICATION_URL, param1,soaParam);
						System.out.println("userRv:"+userRv);
						if(userRv != null && userRv.getStatus() == ResultStatus.SUCCESS_STATUS){
							JSONArray user = JSONArray.parseObject(userRv.getDataString(), JSONArray.class);
							List<JSONObject> userList = (List<JSONObject>)userRv.getData();
							merchant.put("mpUser", userList.get(0));
						}
						//获取店铺mcode
						List<MerchantStore> merchantStores = merchantStoreDao.getByMerId(merId);
						if (merchantStores!=null&&merchantStores.size()>0) {
							JSONArray stores = new JSONArray();
							for (MerchantStore merchantStore : merchantStores) {
								String mcode = merchantStore.getMcode();
								if (!StringUtils.isEmpty(mcode)) {
									//根据mcode调取商户平台接口，循环获取店铺详情
									JSONObject param2 = new JSONObject();
									param2.put("mcode", mcode);
									param2.put("searchMerByMcode", true);
									System.out.println("根据Mcode获取门店信息接口参数："+param2.toString());
									ResponseValue res = SOAUtil.getResValFromSOA(WMP_PROVIDER_APP_CODE, WMP_USER_STORES_URL, param2,soaParam);
									System.out.println("agent-res:"+res);
									if(res != null && res.getStatus() == ResultStatus.SUCCESS_STATUS){
										List<JSONObject> storesData = (List<JSONObject>)res.getData();
										//System.out.println("--storesData----"+storesData);
										if (storesData!=null&&storesData.size()>0) {
											JSONObject store = storesData.get(0);
											//添加店铺所属代理商字段信息
											/*store.put("salesName", sales.getName());
											store.put("salesPhone", sales.getPhone());*/
											for (JSONObject store1 : storesData) {
												//System.out.println("--store1----"+store1);
												String m = store1.get("mcode").toString();
												if(mcode.equals(m)){
													//System.out.println("--agent.getName()----"+agent.getName()+"-----agent.getContactPhone()---"+agent.getContactPhone());
													store1.put("salesName", agent.getName());
													store1.put("salesPhone", agent.getContactPhone());
													stores.add(store1);
												}
											}
										}
										/*stores.add(store);*/
										
									}
								}
							}
							merchant.put("stores", stores);
						}
					}
					merchants.add(merchant);
				}
			}
			
		}
		
		
		
		//根据用户查询业务员
		List<Sales> saleses = salesService.getByUserForMerchant(userId);
		//System.out.println("saleses:"+saleses.toString());
		//根据业务员循环查询商户
		if (saleses!=null&&saleses.size()>0) {
			for (Sales sales : saleses) {
				List<SaleMerchant> saleMerchants = saleMerchantDao.getBySale(sales.getId().longValue());
				
				if (saleMerchants!=null&&saleMerchants.size()>0) {
					//循环获取商户id
					for (SaleMerchant saleMerchant : saleMerchants) {
						JSONObject merchant = new JSONObject();
						String merId = saleMerchant.getMerId();
						merchant.put("qualificationId", merId);
						if (!StringUtils.isEmpty(merId)) {
							//调取商户平台接口，获取商户平台用户信息
							
							JSONObject param1 = new JSONObject();
							param1.put("qualificationId", merId);
							ResponseValue userRv = SOAUtil.getResValFromSOA(WMP_PROVIDER_APP_CODE, WMP_USER_BY_QUALIFICATION_URL, param1,soaParam);
							System.out.println("userRv:"+userRv);
							if(userRv != null && userRv.getStatus() == ResultStatus.SUCCESS_STATUS){
								JSONArray user = JSONArray.parseObject(userRv.getDataString(), JSONArray.class);
								List<JSONObject> userList = (List<JSONObject>)userRv.getData();
								merchant.put("mpUser", userList.get(0));
							}
							
							//获取mcode
							List<MerchantStore> merchantStores = merchantStoreDao.getByMerId(merId);
							if (merchantStores!=null&&merchantStores.size()>0) {
								JSONArray stores = new JSONArray();
								for (MerchantStore merchantStore : merchantStores) {
									String mcode = merchantStore.getMcode();
									if (!StringUtils.isEmpty(mcode)) {
										
										
										//根据mcode调取商户平台接口，循环获取店铺详情
										
										JSONObject param2 = new JSONObject();
										param2.put("mcode", mcode);
										param2.put("searchMerByMcode", true);
										System.out.println("根据Mcode获取门店信息接口参数："+param2.toString());
										ResponseValue res = SOAUtil.getResValFromSOA(WMP_PROVIDER_APP_CODE, WMP_USER_STORES_URL, param2,soaParam);
										System.out.println("sales-res:"+res);
										if(res != null && res.getStatus() == ResultStatus.SUCCESS_STATUS){
											
											List<JSONObject> storesData = (List<JSONObject>)res.getData();
											
											if (storesData!=null&&storesData.size()>0) {
												JSONObject store = storesData.get(0);
												//添加店铺所属业务员字段信息
												/*store.put("salesName", sales.getName());
												store.put("salesPhone", sales.getPhone());*/
												for (JSONObject store1 : storesData) {
													String m = store1.get("mcode").toString();
													if(m.equals(mcode)){
														store1.put("salesName", sales.getName());
														store1.put("salesPhone", sales.getPhone());
														stores.add(store1);
													}
												}
											}
											/*stores.add(store);*/
											
										}
										
									}
									
								}
								merchant.put("stores", stores);
								
							}
						}
						merchants.add(merchant);
					}
				}
			}
		}
		
		return merchants;
	}
	/**
	 * 根据商户mcode查询商户列表
	 * @param userId
	 * @param mcode
	 * @return
	 */
	public JSONObject getMerchantByMcode(Integer userId, String mcode) {
		JSONObject merchant = new JSONObject();
		//获取商户merId
		MerchantStore merchantStore = merchantStoreDao.getByMcode(mcode);
		if (merchantStore==null) {
			return null;
		}
		String merId = merchantStore.getMerId();
		//根据商户查询代理商
		AgentMerchant agentMerchant = agentMerchantDao.getByMerId(merId);
		//根据商户查询业务员
		SaleMerchant saleMerchant =  saleMerchantDao.getByMerId(merId);
		if (saleMerchant==null&&agentMerchant==null) {
			return null;
		}
		JSONObject soaParam = SoaConfig.getSoaParam();
		JSONObject params = new JSONObject();
		//获取代理商信息
		if (agentMerchant!=null) {
			Long agentId = agentMerchant.getAgentId();
			Agent agent = agentDao.getById(agentId.intValue());
			//调取商户平台接口，查询平台账户信息
			
			params.put("mcode", mcode);
			params.put("searchMerByMcode", true);
			
			ResponseValue res = SOAUtil.getResValFromSOA(WMP_PROVIDER_APP_CODE, WMP_USER_STORES_URL, params,soaParam);
		    System.out.println("---merchant/getUserMerchantByWhereByMcode:"+res.toString());
		    if(res != null && res.getStatus() == ResultStatus.SUCCESS_STATUS){
		    	//JSONArray stores = JSONArray.parseObject(res.getDataString(), JSONArray.class);
		    	
		    	List<JSONObject> stores = (List<JSONObject>)res.getData();
		    	JSONObject store = stores.get(0);
		    	//添加店铺所属代理商字段信息
			    if (agent!=null) {
				    store.put("salesName", agent.getName());
				    store.put("salesPhone", agent.getContactPhone());
				}
		    	/*//添加店铺所属业务员字段信息
		    	if (sales!=null) {
		    		store.put("salesName", sales.getName());
		    		store.put("salesPhone", sales.getPhone());
					
				}*/
	        	merchant.put("stores", stores);
			}
			
		}
		if (saleMerchant!=null) {
			//获取业务员信息
			Long saleId = saleMerchant.getSaleId();
			Sales sales = salesDao.getById(new Integer(saleId.intValue()));
			
			//调取商户平台接口，查询平台账户信息
			params.put("mcode", mcode);
			params.put("searchMerByMcode", true);
			
			ResponseValue res = SOAUtil.getResValFromSOA(WMP_PROVIDER_APP_CODE, WMP_USER_STORES_URL, params,soaParam);
		    System.out.println("---merchant/getUserMerchantByWhereByMcode:"+res.toString());
		    if(res != null && res.getStatus() == ResultStatus.SUCCESS_STATUS){
		    	//JSONArray stores = JSONArray.parseObject(res.getDataString(), JSONArray.class);
		    	
		    	List<JSONObject> stores = (List<JSONObject>)res.getData();
		    	JSONObject store = stores.get(0);
		    	//添加店铺所属代理商字段信息
			    /*if (agent!=null) {
				    store.put("salesName", agent.getName());
				    store.put("salesPhone", agent.getContactPhone());
				}*/
		    	//添加店铺所属业务员字段信息
		    	if (sales!=null) {
		    		store.put("salesName", sales.getName());
		    		store.put("salesPhone", sales.getPhone());
					
				}
	        	merchant.put("stores", stores);
			}
		}
		
	    params.clear();
	    params.put("qualificationId", merId);
	    ResponseValue userRes = SOAUtil.getResValFromSOA(WMP_PROVIDER_APP_CODE, WMP_USER_BY_QUALIFICATION_URL, params,soaParam);
	    System.out.println("---user/getUserByQualificationId:"+userRes.toString());
	    if(userRes != null && userRes.getStatus() == ResultStatus.SUCCESS_STATUS){
	    	JSONArray user = JSONArray.parseObject(userRes.getDataString(), JSONArray.class);
	    	List<JSONObject> userList = (List<JSONObject>)userRes.getData();
	    	merchant.put("mpUser", userList.get(0));
	    }
	    merchant.put("qualificationId", merId);
		return merchant;
	}

	/**
	 * 根据商户平台登录手机号查询商户列表
	 * @param userId
	 * @param phone
	 * @param sales
	 * @return
	 */
	public JSONObject getMerchantByPhone(Integer userId,String phone){
		JSONObject merchant = new JSONObject();
		JSONObject soaParam = SoaConfig.getSoaParam();
	    JSONObject params = new JSONObject();
	    //根据手机号获取商户平台用户信息
	    params.put("mobile", phone);
	    ResponseValue userRes = SOAUtil.getResValFromSOA(WMP_PROVIDER_APP_CODE, WMP_MERCHANT_SEARCH_URL, params,soaParam);
	    //System.out.println("---user/getUserByMobile:"+userRes.toString());
	    if(userRes != null && userRes.getStatus() == ResultStatus.SUCCESS_STATUS){
	    	JSONObject user = JSONObject.parseObject(userRes.getDataString(), JSONObject.class);
	    	String merId = user.get("merId").toString();
	    	if (!StringUtils.isEmpty(merId)) {
				//商户属于哪位商户开通
	    		AgentMerchant agentMerchant = agentMerchantDao.getByMerId(merId);
	    		if (agentMerchant!=null) {
					merchant.put("qualificationId", merId);
					merchant.put("mpUser", user);
					//查询店铺信息
					params.put("isAll", true);
					params.put("qualificationId", merId);
					ResponseValue res = SOAUtil.getResValFromSOA(WMP_PROVIDER_APP_CODE, WMP_USER_STORES_URL, params,soaParam);
					if (res!=null&&res.getStatus()==ResultStatus.SUCCESS_STATUS) {
						//解析出店铺信息
						List<JSONObject> stores = (List<JSONObject>)res.getData();
						
						Agent agent = agentDao.getById(new Integer(agentMerchant.getAgentId().intValue()));
						for (JSONObject store : stores) {
							store.put("salesName", agent.getName());
							store.put("salesPhone", agent.getContactPhone());
						}
						merchant.put("stores", stores);
					}
					return merchant;
				}
	    		//商户属于哪位业务员开通
	    		SaleMerchant saleMerchant = saleMerchantDao.getByMerId(merId);
	    		if (saleMerchant!=null) {//业务员存在
	    			merchant.put("qualificationId", merId);
	    			merchant.put("mpUser", user);
	    			//查询出店铺信息
	    			params.clear();
	    			params.put("isAll", true);
	    			params.put("qualificationId", merId);
	    			ResponseValue res = SOAUtil.getResValFromSOA(WMP_PROVIDER_APP_CODE, WMP_USER_STORES_URL, params,soaParam);
	    			//System.out.println("---merchant/getUserMerchantByWhere:"+res.toString());
	    			if(res != null && res.getStatus() == ResultStatus.SUCCESS_STATUS){
	    				//解析出店铺信息
	    				List<JSONObject> stores = (List<JSONObject>)res.getData();
	    				
	    				Sales sale = salesDao.getById(new Integer(saleMerchant.getSaleId().intValue()));
	    				for (JSONObject store : stores) {
	    					store.put("salesName", sale.getName());
	    					store.put("salesPhone", sale.getPhone());
	    				}
	    				merchant.put("stores", stores);
	    				
	    			}
	    			return merchant;
	    		}
	    		
			}
	    }
	    return null;
	}
	/**
	 * 判断商户是否由业务员生成（备用）
	 * @param sales
	 * @param merId
	 * @return
	 */
	/*
	public static Boolean isExit(List<Sales> sales,String merId){
		if (sales!=null&&sales.size()>0) {
			for (Sales sale : sales) {
				//获取商户Id
				List<SaleMerchant> saleMerchants = saleMerchantDao.getBySale(sale.getId().longValue());
				for (SaleMerchant saleMerchant : saleMerchants) {
					String merIdValue = saleMerchant.getMerId();
					//判断从商户平台查询出的商户merId是否存在于本地商户记录
					if (!StringUtils.isEmpty(merId)&&merId.equals(merIdValue)) {
						return true;
					} 
				}
			}
		}
		return false;
	}
	*/
	
	/**
     * 根据手机号获取商户信息
     * @param phone
     * @return
     */
    @Override
    public JSONObject getMerchant(String phone) {

        JSONObject soaParam = SoaConfig.getSoaParam();
        JSONObject params = new JSONObject();
        params.put("mobile", phone);
        ResponseValue res = SOAUtil.getResValFromSOA(WMP_PROVIDER_APP_CODE, WMP_MERCHANT_SEARCH_URL, params,soaParam);
        if (res != null){
            if(res.getStatus() == ResultStatus.SUCCESS_STATUS){
                return (JSONObject) res.getData();
            }else if(res.getStatus() == ResultStatus.NO_VALUE_STATUS){
                return null;
            }else {
                throw BusinessException.createInstance(BusinessErrorType.MERCHANT_REGISTER_ERROR);
            }
        }else{
            throw BusinessException.createInstance(BusinessErrorType.MERCHANT_REGISTER_ERROR);
        }
    }
    
	/**
     * 注册商户
     * @param phone
     * @return
     */
    @Override
    public JSONObject register(String phone,String password) throws BusinessException{

        JSONObject soaParam = SoaConfig.getSoaParam();
        String passwordMD5 = MD5.getMD5(password.getBytes()).toLowerCase();
        JSONObject params = new JSONObject();
        params.put("mobile", phone);
        params.put("password", passwordMD5);
        params.put("userType",USERTYPE);
        params.put("isAdmin", ISADMIN);//1:小微商户
        ResponseValue res = SOAUtil.getResValFromSOA(WMP_PROVIDER_APP_CODE, WMP_MERCHANT_REGISTER_URL, params,soaParam);
        if (res != null){
            if(res.getStatus() == ResultStatus.SUCCESS_STATUS){
                return (JSONObject) res.getData();
            }else {
                throw BusinessException.createInstance(BusinessErrorType.MERCHANT_REGISTER_ERROR);
            }
        }else{
            throw BusinessException.createInstance(BusinessErrorType.MERCHANT_REGISTER_ERROR);
        }
    }
    
    /**
     * 新注册用户资质认证
     * @param phone
     * @param uid
     * @return
     */
    @Override
    public String addQualification(String phone, String uid) {

        JSONObject soaParam = SoaConfig.getSoaParam();
        JSONObject params = new JSONObject();
        params.put("uid", uid);
        params.put("merName",phone);
        params.put("checkStatus",2);
        ResponseValue res = SOAUtil.getResValFromSOA(WMP_PROVIDER_APP_CODE, WMP_QUALIFICATION_ADD_URL, params,soaParam);
        if (res != null){
            if(res.getStatus() == ResultStatus.SUCCESS_STATUS){
                return (String) res.getData();
            }else {
                throw BusinessException.createInstance(BusinessErrorType.MERCHANT_REGISTER_ERROR);
            }
        }else{
            throw BusinessException.createInstance(BusinessErrorType.MERCHANT_REGISTER_ERROR);
        }
    }

}
